<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="css/mui.css" rel="stylesheet" />
	</head>

	<body>
		
		<div>
			<input id="message-value" type="text" placeholder="请输入消息"/> 
			<button id="send" type="button">发送</button>
			<button id="open" type="button">打开连接</button>
			<button id="close" type="button">关闭连接</button>
		</div>
		<hr >
		<div id="receive-message-div">
			
		</div>
		
		
		
		
		
		<script src="js/mui.js"></script>
		<script type="text/javascript">
			mui.init()
			
			window.CHAT = {
				socket: null,
				init: function() {
					if (window.WebSocket) {
						CHAT.socket = new WebSocket('ws://192.168.222.112:8088/ws');
						CHAT.socket.onopen = function() {
							console.log('websocket连接已经打开');
						};
						CHAT.socket.onclose = function() {
							console.log('websocket连接已经关闭');
						};
						CHAT.socket.onmessage = function(e) {
							let messageDiv = document.getElementById('receive-message-div');
							let html = messageDiv.innerHTML;
							messageDiv.innerHTML = html + '<hr />' + e.data;
							
							let placeHolder = document.getElementById('message-value');
							placeHolder.value = '';	
						};
						CHAT.socket.onerror = function() {
							console.error('连接出错');
						};
					} else {
						alert('你的浏览器不支持websocket');
					}
				},
				chat: function() {
					const message = document.getElementById('message-value').value;
					if (message) {
						CHAT.socket.send(message);
					} else {
						console.log('请输入内容');
					}
					
				},
				close: function() {
					CHAT.socket.close();
				}
			};
			
			CHAT.init();
			
			document.getElementById('send').addEventListener('click', function() {
				CHAT.chat();
			});
			document.getElementById('open').addEventListener('click', function() {
				if (CHAT.socket.readyState !== 3) {
					return;
				}
				CHAT.init();
			});
			document.getElementById('close').addEventListener('click', function() {
				CHAT.close();
			});
			
		</script>
	</body>

</html>
